<template>
  <el-dialog v-model="visible" :title="title" width="50%">
    <el-form
      ref="form"
      :inline="true"
      label-position="top"
      style="width: 100%"
      :model="formState"
      :rules="rules"
    >
      <el-row style="width: 100%">
        <el-col
          :span="item.span"
          :key="item.field"
          v-for="item in config"
          style="width: 100%"
        >
          <el-form-item
            :label="item.label"
            class="left-align-label"
            :prop="item.field"
          >
            <el-input
              v-if="item.component === 'Input'"
              v-model="formState[item.field]"
              v-bind="item.componentProps"
            >
            </el-input>
            <el-select
              v-if="item.component === 'Select'"
              v-model="formState[item.field]"
              v-bind="item.componentProps"
            >
              <el-option
                :label="jtem.label"
                :value="jtem.value"
                :key="jtem.value"
                v-for="jtem in item.componentProps.options"
              ></el-option>
            </el-select>

            <div v-if="item.component === 'CSelect'" class="flex">
              <el-input
                v-model="formState[item.field]"
                v-bind="item.componentProps"
                placeholder="请输入"
              >
                <template #prepend>
                  <el-select
                    v-model="formState[item.field]"
                    placeholder="请选择"
                    style="width: 115px"
                  >
                    <el-option
                      :label="jtem.label"
                      :value="jtem.value"
                      :key="jtem.value"
                      v-for="jtem in item.componentProps.options"
                    ></el-option>
                  </el-select>
                </template>
              </el-input>
            </div>
            <el-date-picker
              v-if="item.component === 'DatePicker'"
              v-model="formState[item.field]"
              v-bind="item.componentProps"
            />
            <el-checkbox-group
              v-if="item.component === 'CheckboxGroup'"
              v-model="formState[item.field]"
              v-bind="item.componentProps"
            >
              <el-checkbox
                :label="jtem.label"
                :value="jtem.value"
                :key="jtem.value"
                v-for="jtem in item.componentProps.options"
              />
            </el-checkbox-group>

            <el-upload
              v-if="item.component === 'Upload'"
              v-model:file-list="formState[item.field]"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :before-upload="beforeUpload"
              :limit="1"
              :auto-upload="false"
              v-bind="item.componentProps"
              :on-exceed="handleExceed"
              accept=".docx,.ppt,.txt,.pdf"
            >
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  只支持.docx,.ppt,.txt,.pdf 格式的文件，且文件大小不能超过 50M
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer v-if="title != '详情'">
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleOk" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose, nextTick, defineProps } from "vue";
import { config, rules, initDic } from "./form.js";
import { uploadFiles } from "@/api/know.js";
import { ElMessage } from "element-plus";

const props = defineProps({
  reset: {
    type: Function,
  },
});

const formState = ref({ file: [] });
const visible = ref(false);
const title = ref("新增");
const loading = ref(false);
const form = ref();
const show = ref(false);

const disabled = () => {
  config.value.forEach((item) => {
    if (title.value === "详情") {
      item.componentProps.disabled = true;
    } else {
      item.componentProps.disabled = false;
    }
  });
};

const handleVisible = async (boolean, name, data) => {
  initDic();
  visible.value = boolean;
  title.value = name;
  formState.value = data;
  disabled();

  // 等待 DOM 更新（表单挂载完成）后，再清空校验
  await nextTick();
  if (form.value) {
    form.value.resetFields(); // 此时能正确找到表单字段
  }
};
defineExpose({
  handleVisible,
});

const handleOk = () => {
  if (title.value === "新增") {
    loading.value = true;
    uploadFiles(formState.value)
      .then((res) => {
        if (res.code == 500) {
          ElMessage({
            message: res.message,
            type: "error",
          });
        } else {
          ElMessage({
            message: "新增成功",
            type: "success",
          });
        }

        visible.value = false;
        props.reset();
      })
      .finally(() => {
        loading.value = false;
      });
  }
};

const UseUploadHooks = () => {
  const handleRemove = (file, uploadFiles) => {
    console.log(file, uploadFiles);
  };

  const handlePreview = (uploadFile) => {
    console.log(uploadFile);
  };

  const handleExceed = (files, uploadFiles) => {};

  const beforeRemove = (uploadFile, uploadFiles) => {};

  // 校验文件大小不能超过50M
  const beforeUpload = (file) => {
    const isLt50M = file.size / 1024 / 1024 < 50;
    if (!isLt50M) {
      ElMessage.error("文件大小不能超过 50M");
      return false;
    }
    return true;
  };

  return {
    handleRemove,
    handlePreview,
    handleExceed,
    beforeRemove,
    beforeUpload,
  };
};

const {
  handleRemove,
  handlePreview,
  handleExceed,
  beforeRemove,
  beforeUpload,
} = UseUploadHooks();
</script>
<style scoped lang="less">
:deep(.el-form-item) {
  width: 100% !important;
}
</style>
